package io.renren.modules.task.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import io.renren.common.exception.RRException;
import io.renren.common.utils.PageUtils;
import io.renren.common.utils.R;
import io.renren.modules.task.entity.MtCcAreaRouteEntity;
import io.renren.modules.task.entity.MtCcEquipmentPointRelatEntity;
import io.renren.modules.task.entity.MtCcWarehousePointEntity;
import io.renren.modules.task.service.MtCcAreaRouteService;
import io.renren.modules.task.service.MtCcEquipmentPointRelatService;
import io.renren.modules.task.service.MtCcWarehousePointService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.shiro.authz.annotation.RequiresPermissions;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.*;

/**
 * @Author: 蔡翔
 * @Date: 2019/9/11 13:34
 * @Version 1.0
 */
@Api(description = "库位点接口")
@RestController
@RequestMapping("/WarehousePoint")
public class MtCcWarehousePointController {
    @Autowired
    private MtCcWarehousePointService mtCcWarehousePointService;

    @Autowired
    private MtCcEquipmentPointRelatService mtCcEquipmentPointRelatService;

    @Autowired
    private MtCcAreaRouteService mtCcAreaRouteService;

    /**
     *  注意 数据库中id 要设置为自增，这里就不用管id了。
     **/
    @ApiOperation(value = "新增加一个库位", notes = "新增加一个库位")
    @PostMapping("/addWarehousingPoint")
    public R addWarehousingPoint(@RequestBody MtCcWarehousePointEntity mtCcWarehousePointEntity) throws RRException{

        if(mtCcWarehousePointEntity.getWarehousepointName()!=null || mtCcWarehousePointEntity.getWarehousepointName()!=""){

            String whName = mtCcWarehousePointEntity.getWarehousepointName();
            Map<String,Object> warehousepointNameMap = new HashMap<>();
            warehousepointNameMap.put("warehousepoint_name",whName);
            List<MtCcWarehousePointEntity> mtCcWarehousePointEntities = mtCcWarehousePointService.getBaseMapper().selectByMap(warehousepointNameMap);
            if(!mtCcWarehousePointEntities.isEmpty()){
                return R.error("这个库位点已经存在，请试试其它点");
            }

            mtCcWarehousePointEntity.setCreateTime(new Date());
            mtCcWarehousePointEntity.setUpdateTime(new Date());
            try {
                mtCcWarehousePointService.save(mtCcWarehousePointEntity);
            }catch (RRException e){
                return R.error("写入数据库异常，请稍后再试");
            }
            return R.ok("新增成功");
        }else {
            return R.error("库位点name 不能为空");
        }
    }

    /**
     *  删除一个库位
     **/
    @ApiOperation(value = "删除一个库位", notes = "删除一个库位")
    @PostMapping("/delWarehousingPoint")
    public R delWarehousingPoint(@RequestBody MtCcWarehousePointEntity mtCcWarehousePointEntity) throws RRException{
        String name = mtCcWarehousePointEntity.getWarehousepointName();
        if(name!=null){
            Map<String,Object> columnMap_pointName = new HashMap<>();
            columnMap_pointName.put("warehousepoint_name",name);
            int result = -1;
            try {
                // 0 - 不成功 ；1 - 成功
                result = mtCcWarehousePointService.getBaseMapper().deleteByMap(columnMap_pointName);
            }catch (RRException e){
                return R.error("操作数据库异常");
            }
            if(result != 1){
                return R.error("删除数据库不成功");
            }
            return R.ok("删除库位点成功");
        }else {
            return R.error("name不能为空");
        }
    }

    /**
     *  查询所有库位点
     **/
    @ApiOperation(value = "查看所有库位", notes = "查看所有库位")
    @GetMapping("/getWarehousingPoint")
    public R getWarehousingPoint() throws RRException{
        List<MtCcWarehousePointEntity> list = null;
        try {
            list = mtCcWarehousePointService.list();
        }catch (Exception e){
            return R.error("操作数据库异常");
        }

        return R.ok().put("data",list);
    }

    /**
     * 查询所有点 分页
     **/
    @ApiOperation(value = "查询所有点 - 分页", notes = "查询所有点 - 分页")
    @RequestMapping("/getWarehousingPointPage")
    public R getWarehousingPointPage(@RequestParam Map<String, Object> params){
        PageUtils page = mtCcWarehousePointService.queryPage(params);
        return R.ok().put("page", page);
    }

    /**
     *  更新库位对应关系
     **/
    @ApiOperation(value = "更细库位对应关系", notes = "更细库位对应关系")
    @GetMapping("/updateWarehousingPointRelate")
    public R updateWarehousingPointRelate() throws RRException{
        List<MtCcWarehousePointEntity> warehousePointList = mtCcWarehousePointService.list();
        Integer warehousePointCount = warehousePointList.size();

        List<MtCcEquipmentPointRelatEntity> equipmentPointRelatList = mtCcEquipmentPointRelatService.list();
        //对mtCcEquipmentPointRelate 这张表进行 更新。
        int i=0;
        for(MtCcEquipmentPointRelatEntity mt :equipmentPointRelatList){
            i = i%warehousePointCount;

            String oldProductStoragePointId = mt.getProductStoragePointId();
            String[] splitOld = oldProductStoragePointId.split("-");

            String newProductStoragePointId = splitOld[0]+"-"+warehousePointList.get(i).getWarehousepointName();

            mt.setProductStoragePointId(newProductStoragePointId);
            i++;
        }
        boolean flagEquipment = false;
        Collection equipmentPointRelatCollect = equipmentPointRelatList;

        try {
             flagEquipment = mtCcEquipmentPointRelatService.saveOrUpdateBatch(equipmentPointRelatCollect);
        }catch (RRException e){
            return R.error("操作数据库异常");
        }

        if(flagEquipment){
            return R.ok("更新成功");
        }else {
            return R.error("更新失败");
        }
/*
        //对mt_cc_area_route 这张表进行 更新。
        // 对A 进行更新 依据source_no字段
        QueryWrapper<MtCcAreaRouteEntity> queryWrapper = new QueryWrapper<MtCcAreaRouteEntity>();
        queryWrapper.like("source_no","A");
        List<MtCcAreaRouteEntity> areaRouteList = mtCcAreaRouteService.getBaseMapper().selectList(queryWrapper);
        int j=0;
        for(MtCcAreaRouteEntity ar :areaRouteList){
            j = j%warehousePointCount;
            String destinationNo =warehousePointList.get(j).getWarehousepointName();

            String routeCodeStr = ar.getSourceNo()+"-"+destinationNo;
            ar.setDestinationNo(destinationNo);
            ar.setRouteCode(routeCodeStr);
            j++;
        }

        boolean flagAreas = false;
        try {
            flagAreas = mtCcAreaRouteService.saveOrUpdateBatch(areaRouteList);
        }catch (RRException e){
            return R.error("操作数据库异常");
        }

        // 对B 进行更新 依据source_no字段
        QueryWrapper<MtCcAreaRouteEntity> queryWrapperB = new QueryWrapper<MtCcAreaRouteEntity>();
        queryWrapperB.like("source_no","B");
        List<MtCcAreaRouteEntity> areaRouteListB = mtCcAreaRouteService.getBaseMapper().selectList(queryWrapperB);
        for(MtCcAreaRouteEntity ar :areaRouteListB){
            j = j%warehousePointCount;
            String destinationNo =warehousePointList.get(j).getWarehousepointName();

            String routeCodeStr = ar.getSourceNo()+"-"+destinationNo;
            ar.setDestinationNo(destinationNo);
            ar.setRouteCode(routeCodeStr);
            j++;
        }

        boolean flagAreasB = false;
        try {
            flagAreasB = mtCcAreaRouteService.saveOrUpdateBatch(areaRouteListB);
        }catch (RRException e){
            return R.error("操作数据库异常");
        }


        if(!flagAreas || !flagAreasB){
            return R.error("更新 对mt_cc_area_route 失败");
        }*/


    }

    /**
     * 查询单条记录
     **/
    @ApiOperation(value = "查询某个库位点 对应的控制台", notes = "查询某个库位点 对应的控制台")
    @PostMapping("/getConsoleInfoByHouseware")
    public R getConsoleInfoByHouseware(@RequestBody MtCcWarehousePointEntity mtCcWarehousePointEntity){

        QueryWrapper<MtCcEquipmentPointRelatEntity> queryWrapper = new QueryWrapper<MtCcEquipmentPointRelatEntity>();
        queryWrapper.like("product_storage_point_id",mtCcWarehousePointEntity.getWarehousepointName());

        List<MtCcEquipmentPointRelatEntity> list = null;
        try {
            list = mtCcEquipmentPointRelatService.getBaseMapper().selectList(queryWrapper);

        }catch (Exception e){
            return R.error("操作数据库异常");
        }

        String result = "";

        for(MtCcEquipmentPointRelatEntity mtCcEquipmentPointRelatEntity:list){
            result += mtCcEquipmentPointRelatEntity.getEquipmentId()+"  ";
        }

        if(!list.isEmpty()){
            return R.ok().put("data",result);
        }else {
            return R.error("没有这个点位对应的控制台");
        }
    }
}
